package
{
	import cfg.SysConfig;
	
	import com.fancy.display.DisplayActivator;
	import com.fancy.framework.BundleContext;
	import com.fancy.framework.BundleManager;
	import com.fancy.logic.LogicActivator;
	import com.fancy.net.NetActivator;
	import com.fancy.ui.UIActivator;
	
	import effects.NormalEffects;
	
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import test.TmpTest;
	
	public class FancyMain extends Sprite
	{
		private const PLUGINS_FOLDER:String = "plugins/";
		private var _pluginsAddr:Array = 
			["com.fancy.framework.swf", "com.fancy.logic.swf", "com.fancy.display.swf", "com.fancy.ui.swf", "com.fancy.net.swf"];
		private var _plugLoader:Loader = new Loader();
		
		public function FancyMain()
		{
			if (stage)
			{
				init();
			}
			else
			{
				addEventListener(Event.ADDED_TO_STAGE, init);
			}
		}
		
		/** 初始化入口 */
		private function init(event:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			SysConfig.setClientScreenParam(this);
			stage.addEventListener(Event.RESIZE, clientRect_resize);
			//
			_plugLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, pluginLoaded);
			loadPlugins();
			//
			initHelper();
		}
		
		private function loadPlugins():void
		{
			trace("FancyMain::loadPlugins()");
			if(_pluginsAddr.length > 0)
			{
				var context:LoaderContext = new LoaderContext();
				context.applicationDomain = ApplicationDomain.currentDomain;
				var url:URLRequest = new URLRequest(PLUGINS_FOLDER + _pluginsAddr[0]);
				_plugLoader.load(url, context);
			}
			else
			{
				_plugLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, pluginLoaded);
				execute();
			}
		}
		
		private function pluginLoaded(event:Event):void
		{
			trace("FancyMain::pluginLoaded(event:Event):void");
			_pluginsAddr.shift();
			loadPlugins();
		}
		
		private function execute():void
		{
			trace("FancyMain::execute():void");
			var context:BundleContext = new BundleContext(this);
			var logic:LogicActivator = new LogicActivator();
			var display:DisplayActivator = new DisplayActivator();
			var ui:UIActivator = new UIActivator();
			var net:NetActivator = new NetActivator();
			logic.start(context);
			display.start(context);
			ui.start(context);
			net.start(context);
			//
			BundleManager.instance.initAllBundles();
		}
		
		/** 做辅助性事宜[仅测试辅助功能，可以任意删除] */
		private function initHelper():void
		{
			trace("FancyMain::initHelper()");
			//TmpTest.addOneTxt(this);
			NormalEffects.giveStageRedBorder(this);
		}
		
		/** 客户区大小改变 */
		private function clientRect_resize(event:Event):void
		{
			NormalEffects.giveStageRedBorder(this);
		}
		
	}
}